<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{.title}}</title>
    <link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<div class="container">
    <h2>文件重命名</h2>
    <div id="form">
        <div class="form-group">
            <button id="btn-folder">选择文件夹</button>
        </div>
        <div class="form-group">
            <label for="prefix">文件名前缀</label>
            <input type="text" id="prefix" name="prefix" placeholder="例如: file_">
        </div>
        <div class="form-group">
            <label for="digit">位数</label>
            <input type="number" id="digit" name="digit" min="1" value="3">
        </div>
        <div class="form-group">
            <label for="initial">初始值</label>
            <input type="number" id="initial" name="initial" min="0" value="1">
        </div>
        <div class="form-group">
            <button id="btn-submit">重命名文件</button>
        </div>
    </div>
</div>
<script>
    document.getElementById('btn-folder').addEventListener('click', async function () {
        try {
            if (!('showDirectoryPicker' in window)) {
                return
            }
            const folderHandle = await window.showDirectoryPicker();
            const files = [];
            for await (const entry of folderHandle.values()) {
                if (entry.kind === 'file') {
                    files.push({
                        handle: entry,
                        name: entry.name
                    });
                }
            }
            files.sort((a, b) => a.name.localeCompare(b.name));
            console.log(files)
        } catch (error) {
            console.error(error)
        }
    });

    document.getElementById('btn-submit').addEventListener('click', function () {
        console.log("btn-submit")
        const folderInput = document.getElementById('folderPath');
        const prefix = document.getElementById('prefix').value;
        const digit = parseInt(document.getElementById('digit').value, 10);
        const initial = parseInt(document.getElementById('initial').value, 10);

        if (folderInput.files.length === 0) {
            alert('请选择一个文件夹');
            return;
        }

        const files = Array.from(folderInput.files);
        console.log(files)
        const folderPath = files[0].webkitRelativePath.split('/')[0];

        files.sort((a, b) => a.webkitRelativePath.localeCompare(b.webkitRelativePath));

        files.forEach((file, index) => {
            const ext = file.name.split('.').pop();
            const newFileName = `${prefix}${(initial + index).toString().padStart(digit, '0')}.${ext}`;
            const newPath = `${folderPath}/${newFileName}`;

            console.log(newPath)
        });
    });
</script>
</body>
</html>
